package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"oa_kadia_link/config"
	"oa_kadia_link/globe"
	"oa_kadia_link/utils"
	"strconv"
)

func Login() gin.HandlerFunc {
	return func(context *gin.Context) {
		var requestBody struct {
			Account *string `json:"account" binding:"required"`
			Password *string `json:"password" binding:"required"`
		}
		utils.CheckRequestBody(context, &requestBody)
		transaction := context.MustGet("transaction").(*gorm.DB)
		var user map[string]interface{}
		transaction.Select("id")
		transaction.Table("users").
			Select("id", "account", "name", "position", "password").
			Where("account = ? and password = ?", requestBody.Account, requestBody.Password).
			Find(&user)
		if _, ok:=user["id"]; !ok {
			globe.FailIpIncr(utils.GetRealIP(context.Request))
			utils.PanicWithErrorJson("账号或密码错误")
		}
		context.Set("userId", user["id"].(int64))
		context.Set("json", gin.H{
			"token": becameToken("userId", user["id"].(int64)),
			"info": user,
		})
	}
}

func becameToken(tokenType string, id int64) string {
	token := fmt.Sprintf("NEFUOA-%d-%s-TOKEN-%s", id, tokenType, utils.RandStr(20))
	globe.GetRdb().Set("["+tokenType+":token]"+strconv.FormatInt(id, 10), token, utils.ToTimeSecond(config.GetStorageTime().Token))
	return token
}
